package com.example.matetest.slice;

import com.example.matetest.ResourceTable;
import com.example.matetest.bean.ImageItem;
import com.example.matetest.bean.PictureItem;
import com.example.matetest.provider.PageProvider;
import com.example.matetest.provider.PictureItemProvider;
import com.example.matetest.slice.home.AboutAbilitySlice;
import com.example.matetest.slice.home.MyInfoAbilitySlice;
import com.example.matetest.slice.home.NetWorkAbilitySlice;
import com.example.matetest.slice.home.SetAbilitySlice;
import de.hdodenhof.circleimageview.CircleImageView;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.ArrayList;
import java.util.List;

public class HomeAbilitySlice extends AbilitySlice implements Component.ClickedListener {
    private static final String TAG = HomeAbilitySlice.class.getSimpleName();
    private static final HiLogLabel logLabel = new HiLogLabel(HiLog.LOG_APP, 0x00001, TAG);

    private int tabLastPosition;
    private TabList tabList;
    private String[] str = {"首页", "图片", "地图", "我的"};
    private TabListSelect listSelect = new TabListSelect();
    private AbilitySlice slice = this;
    private Component componentLayout;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_home);

        tabList = (TabList) findComponentById(ResourceTable.Id_tab_list_bottom);
        for (int i = 0; i < str.length; i++) {
            TabList.Tab tab = tabList.new Tab(getContext());
            tab.setText(str[i]);
            tabList.addTab(tab);
        }
        tabList.setFixedMode(true);
        tabList.addTabSelectedListener(listSelect);
        //默认第一个被选中
        tabList.getTabAt(0).select();

        HiLog.info(logLabel, "log_label_msg");
    }


    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onClick(Component component) {
        if (component == circleHead) {
            present(new MyInfoAbilitySlice(), new Intent());

        } else if (component == mAbout) {
            present(new AboutAbilitySlice(), new Intent());

        } else if (component == mSet) {
            present(new SetAbilitySlice(), new Intent());

        } else if (component == mWebView) {
            Intent intent = new Intent();
            Operation operation = new Intent.OperationBuilder()
                    .withDeviceId("")
                    .withBundleName("com.example.matetest")
                    .withAbilityName("com.example.matetest.WebViewAbility")
                    .build();
            intent.setOperation(operation);
            startAbility(intent);
        } else if (component == goToNetwork) {
            present(new NetWorkAbilitySlice(), new Intent());
        }
    }

    class TabListSelect implements TabList.TabSelectedListener {

        @Override
        public void onSelected(TabList.Tab tab) {
            // 当某个Tab从未选中状态变为选中状态时的回调
            ComponentContainer container = (ComponentContainer) findComponentById(ResourceTable.Id_tab_container);

            //根据tab接收的数据，匹配字符串，选择相应功能
            if (tab.getText().equals("首页")) {
                container.removeAllComponents();
                componentLayout = LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_ability_home_host, null, false);
                implementHome(componentLayout);
                container.addComponent(componentLayout);
            } else if (tab.getText().equals("图片")) {
                container.removeAllComponents();
                componentLayout = LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_ability_home_picture, null, false);
                implementPicture(componentLayout);
                container.addComponent(componentLayout);
            } else if (tab.getText().equals("地图")) {
                container.removeAllComponents();
                componentLayout = LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_ability_home_map, null, false);
                implementMap(componentLayout);
                container.addComponent(componentLayout);
            } else if (tab.getText().equals("我的")) {
                container.removeAllComponents();
                componentLayout = LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_ability_home_me, null, false);
                implementMe(componentLayout);
                container.addComponent(componentLayout);
            }

        }

        @Override
        public void onUnselected(TabList.Tab tab) {
            // 当某个Tab从选中状态变为未选中状态时的回调
            tabLastPosition = tab.getPosition();
        }

        @Override
        public void onReselected(TabList.Tab tab) {
            // 当某个Tab已处于选中状态，再次被点击时的状态回调
        }
    }

    /**
     * 首页
     */

    private Text search;
    private SearchBar searchBar;

    private PageProvider pageProvider;
    private PageSlider pageSlider;
    private RadioContainer radioContainer;

    private List<ImageItem> imageItems = new ArrayList<>();
    private int[] images = {
            ResourceTable.Media_host_page1,
            ResourceTable.Media_host_page2,
            ResourceTable.Media_host_page3,
            ResourceTable.Media_host_page4,
    };

    public void implementHome(Component componentLayout) {
        search = (Text) componentLayout.findComponentById(ResourceTable.Id_tv_search);
        searchBar = (SearchBar) componentLayout.findComponentById(ResourceTable.Id_sb_search_bar);

        pageSlider = (PageSlider) componentLayout.findComponentById(ResourceTable.Id_ps_page_slider);
        radioContainer = (RadioContainer) componentLayout.findComponentById(ResourceTable.Id_rc_radio_container);
        //初始化图片和文字数据封装在集合中
        initPage();
        ((RadioButton) radioContainer.getComponentAt(0)).setChecked(true);
        //创建适配器对象，将当前界面对象和封装好的集合发送过去
        pageProvider = new PageProvider(imageItems, this);
        //将适配器加载至滑动组件上，完成同步组装
        pageSlider.setProvider(pageProvider);
        pageSlider.setPageSwitchTime(2000);
        pageSlider.addPageChangedListener(new PageSlider.PageChangedListener() {
            @Override
            public void onPageSliding(int i, float v, int i1) {

            }

            @Override
            public void onPageSlideStateChanged(int i) {

            }

            @Override
            public void onPageChosen(int i) {
                ((RadioButton) radioContainer.getComponentAt(i)).setChecked(true);
            }
        });

        radioContainer.setMarkChangedListener(new RadioContainer.CheckedStateChangedListener() {
            @Override
            public void onCheckedChanged(RadioContainer radioContainer, int i) {
                pageSlider.setCurrentPage(i);
            }
        });
    }

    private void initPage() {
        for (int i = 0; i < images.length; i++) {
            ImageItem imageItem = new ImageItem(images[i]);
            imageItems.add(imageItem);
        }
    }


    /**
     * 图片
     */
    private ListContainer listContainer;

    public void implementPicture(Component componentLayout) {
        listContainer = (ListContainer) componentLayout.findComponentById(ResourceTable.Id_lc_list_container);
        List<PictureItem> list = getData();
        PictureItemProvider pictureItemProvider = new PictureItemProvider(list, this);
        listContainer.setItemProvider(pictureItemProvider);
        list.add(new PictureItem("图片Item" + pictureItemProvider.getCount()));


        listContainer.setBindStateChangedListener(new Component.BindStateChangedListener() {
            @Override
            public void onComponentBoundToWindow(Component component) {
                // ListContainer初始化时数据统一在provider中创建，不直接调用这个接口；
                // 建议在onComponentBoundToWindow监听或者其他事件监听中调用。
                pictureItemProvider.notifyDataChanged();
            }

            @Override
            public void onComponentUnboundFromWindow(Component component) {
            }
        });

        // 点击
        listContainer.setItemClickedListener((container, component, position, id) -> {
            PictureItem item = (PictureItem) listContainer.getItemProvider().getItem(position);
            new ToastDialog(this)
                    .setText("you clicked:" + item.getName())
                    // Toast显示在界面中间
                    .setAlignment(LayoutAlignment.CENTER)
                    .show();
        });

        // 长按点击
        listContainer.setItemLongClickedListener((container, component, position, id) -> {
            PictureItem item = (PictureItem) listContainer.getItemProvider().getItem(position);
            new ToastDialog(this)
                    .setText("you long clicked:" + item.getName())
                    .setAlignment(LayoutAlignment.CENTER)
                    .show();
            return false;
        });
    }

    private ArrayList<PictureItem> getData() {
        ArrayList<PictureItem> list = new ArrayList<>();
        for (int i = 0; i <= 19; i++) {
            list.add(new PictureItem("图片Item" + i));
        }
        return list;
    }


    /**
     * 地图
     */
    private Text goToNetwork;

    public void implementMap(Component componentLayout) {
        goToNetwork = (Text) componentLayout.findComponentById(ResourceTable.Id_tv_go_to_network);
        goToNetwork.setClickedListener(this);
    }

    /**
     * 我的
     */

    private CircleImageView circleHead;
    private Text userName;
    private Text phoneNumber;

    private DirectionalLayout mAbout;
    private DirectionalLayout mSet;
    private DirectionalLayout mWebView;

    public void implementMe(Component componentLayout) {
        circleHead = (CircleImageView) componentLayout.findComponentById(ResourceTable.Id_civ_icon);
        userName = (Text) componentLayout.findComponentById(ResourceTable.Id_tv_user_name);
        phoneNumber = (Text) componentLayout.findComponentById(ResourceTable.Id_tv_phone_number);
        circleHead.setClickedListener(this);

        mAbout = (DirectionalLayout) componentLayout.findComponentById(ResourceTable.Id_dl_about);
        mSet = (DirectionalLayout) componentLayout.findComponentById(ResourceTable.Id_dl_set);
        mWebView = (DirectionalLayout) componentLayout.findComponentById(ResourceTable.Id_dl_webView);
        mAbout.setClickedListener(this);
        mSet.setClickedListener(this);
        mWebView.setClickedListener(this);

    }


}
